<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const obj1 = {
        age: 12,
        name: 'aaa',
        fn: function () {
          console.log('aaa')
        },
      }
      obj1.obj = obj1
      const obj2 = {
        age: 12,
        name: 'aaa',
        fn: function () {
          console.log('aaa')
        },
      }
      obj2.obj = obj2
      function betterObj(obj1, obj2) {
        const cache = new WeakMap()
        function _betterObj(obj1, obj2) {
          if (obj1 === obj2) {
            return true
          }
          if (
            typeof obj1 !== 'object' ||
            typeof obj1 === 'null' ||
            typeof obj2 !== 'object' ||
            typeof obj2 === 'null'
          ) {
            return false
          }
          const existing = cache.get(obj1)
          if (existing) {
            return existing === obj2
          }
          cache.set(obj1, obj2)
          const keys1 = Object.keys(obj1)
          const keys2 = Object.keys(obj2)
          if (keys1.length !== keys2.length) {
            return false
          }
          for (var key of keys1) {
            if (!keys2.includes(key)) {
              return false
            }
            if (
              typeof obj1[key] === 'function' &&
              typeof obj2[key] === 'function'
            ) {
              if (obj1[key].toString() !== obj2[key].toString()) {
                return false
              }
            } else {
              if (!_betterObj(obj1[key], obj2[key])) {
                return false
              }
            }
          }
          return true
        }
        return _betterObj(obj1, obj2)
      }
      console.log(betterObj(obj1, obj2))

      function buildTree(data, parentId = null) {
        let children = []
        data.forEach((item) => {
          if (item.pid === parentId) {
            let childTree = buildTree(data, item.id)
            if (childTree.length) {
              item.children = childTree
            }
            children.push(item)
          }
        })
        return children
      }

      // 示例数据
      const data = [
        { id: 1, pid: null, name: 'Root' },
        { id: 2, pid: 1, name: 'Child 1' },
        { id: 3, pid: 1, name: 'Child 2' },
        { id: 4, pid: 2, name: 'Grandchild 1' },
      ]

      // 构建树
      const tree = buildTree(data)
      // console.log(tree)
    </script>
  </body>
</html>
